package cn.itsource.controller;

import cn.itsource.bean.Department;
import cn.itsource.bean.Student;
import cn.itsource.query.DepartmentQuery;
import cn.itsource.service.IDepartmentService;
import cn.itsource.tree.TreeUtil;
import cn.itsource.util.JsonResult;
import cn.itsource.util.JxlsUtils;
import cn.itsource.util.MyUtils;
import lombok.extern.slf4j.Slf4j;
import org.jxls.util.Util;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * @author : 张金铭
 * @description :
 * @create :2022-11-07 11:58:00
 */
@Slf4j
@RestController
@RequestMapping("/dept")
public class DepartmentController {



    @Resource //j2ee
    private IDepartmentService departmentService;


    @PostMapping("/expect")
    public void expect(HttpServletResponse response) throws IOException {

        List<Student> dataList = generateData();
        String fileName = "test.xlsx";
        HashMap<String, Object> map = new HashMap<>();
        map.put("dataList",dataList);
        response.addHeader("Content-Disposition", "attachment; filename=\"" + "out.xlsx" + "\"");
        JxlsUtils.exportExcelWithOS(response.getOutputStream(), fileName, map);
    }

    private static List<Student> generateData() throws IOException {
        // 生成随机数据
        List<Student> dataList = new ArrayList<>();
        Random random = new Random();
        String imageUrl = "https://img-home.csdnimg.cn/images/20230626085553.jpeg";
        String outputPath = "D:\\Java\\Javawork\\JavaWeb\\pethome\\src\\main\\resources\\img.png"; // 指定输出路径和文件名
        URL url = new URL(imageUrl);

        try (InputStream inputStream = new FileInputStream("C:\\Users\\31801\\Pictures\\Saved Pictures\\blog头像.png");
                     FileOutputStream fos = new FileOutputStream(outputPath)) {

            byte[] bytes = Util.toByteArray(inputStream);
            fos.write(bytes);  // 将图片数据写入输出流
            for (int i = 0; i < 10; i++) {
                Student student = new Student();
                student.setName("姓名" + (i + 1));
                student.setAge(random.nextInt(30) + 20);  // 年龄范围在20-50岁之间
                student.setSchool("学校" + (i + 1));
                student.setImg(bytes);

                dataList.add(student);
            }
        }
        return dataList;
    }



    @GetMapping("/all")
    public JsonResult getAll(){
        List<Department> list = departmentService.list();
        return JsonResult.success(list);
    }


    /**
     * 单个删除
     * @param id
     * @return
     */
    @PostMapping("/{id}")
    public JsonResult deleteByIds(@PathVariable("id") Long id){
//        for (Long id: ids
//             ) {
//            System.out.println(id);
//        }
//        boolean byId = departmentService.removeById(id);
//        if (byId){
//            return JsonResult.success("删除成功");
//        }{
//            return JsonResult.error("删除失败");
//        }
        departmentService.removerTree(id);

        return JsonResult.success("删除成功");
    }


    @PostMapping("/findPage")
    public JsonResult findPage(@RequestBody DepartmentQuery query){
//        log.info("queryPage,{}",query.getPage());
        return departmentService.getPage(query);
    }

    @PostMapping("/state")
    public JsonResult changeState(@RequestBody Department department){
//        log.info("state,{}",department.toString());
        JsonResult result = departmentService.updateState(department);
        return result;
    }



    @PostMapping("/add")
    public JsonResult saveOrUp(@Valid @RequestBody Department department){



//        System.out.println(department);
        if (department.getId()!=null){

            if (department.getParentInts()!=null){
                if (MyUtils.isRepeat(department.getId(),department.getParentInts())) {
                   return JsonResult.error("上级部门不可以选择自己");
                }
            }
            departmentService.updateAllDir(department);
            return JsonResult.success("更新成功");

        }else {
            List<Long> parentInts = department.getParentInts();
            //获取到所有的路径，倒数第一个是上级级部门，最后将所有的拼凑成/xx/xx字符串存放
            //获取上级部门号
            if (parentInts!=null&&parentInts.size()>0) {
                Long lastInts = parentInts.get(parentInts.size() - 1);
                department.setParentId(lastInts);
            }
            //将路径拼接起来  定义的工具类
            String dirPath = MyUtils.getDir(parentInts);

            //调用封装好的方法
            department.setDirPath(dirPath);


            boolean save = departmentService.getId(department);
            if (save){
                return JsonResult.success("保存成功");
            }else {
                return JsonResult.error("保存失败");
            }
        }
    }


    @GetMapping("/getOne/{id}")
    public JsonResult getOne(@PathVariable("id") Long id){
        Department byId = departmentService.getById(id);
        String dirPath = byId.getDirPath();
        List<Long> list = null;
        if (dirPath!=null){
            list = MyUtils.getList(dirPath);
        }
        if (list!=null){
            return JsonResult.success(list);
        }
        return JsonResult.error("请求失败");
    }






    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        log.info("id:{}",id);

        return null;
    }

    /**
     * 获取树形部门数据
     * @return
     */
    @GetMapping("/tree")
    public JsonResult getTree(){
        //查询所有的部门
        List<Department> list = departmentService.list();
        //将所有的部门的dir转化为集合存储
//        List<Department> collect = (List<Department>) list.stream().map(item -> {
//            String dirPath = item.getDirPath();
//            List<Long> dirList = MyUtils.getList(dirPath);
//            //重新存入
//            item.setParentInts(dirList);
//            return item;
//        }).collect(Collectors.toList());

        //调用工具类方法
        List<Department> tree = TreeUtil.getTree(list);
        return JsonResult.success(tree);
    }


    @GetMapping("/getFirst")
    public JsonResult getFirst(){
        //查询所有的上级部门
        JsonResult result = departmentService.getFirst();
        return result;
    }


}
